package com.etoak.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.entity.Schedule;
import com.etoak.entity.ScheduleDTO;
import com.etoak.mapper.ScheduleMapper;
import com.etoak.service.ScheduleService;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule>implements ScheduleService {
    @Override
    public void add(ScheduleDTO schedule) {
        // 获取开始时间
        SimpleDateFormat ff=new SimpleDateFormat("yyyy-MM-dd");
        Date startTime= null;
        Date endTime= null;
        try {
            startTime = ff.parse(schedule.getStartTime());
            endTime = ff.parse(schedule.getEndTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //计算相差天数
        long daysBetween = endTime.getTime()-startTime.getTime();
        daysBetween = daysBetween / (24 * 60 * 60 * 1000)+1;
        //循环插入
        for(int i=1;i<=daysBetween;i++){
            //往数据库中插入数据
            Schedule sch=new Schedule();
            sch.setTimeSlot(schedule.getTimeSlot());
            sch.setTotal(schedule.getTotal());
            sch.setRemaining(schedule.getTotal());
            sch.setDoctorId(schedule.getDoctorId());
            sch.setWorkDate(ff.format(new Date((startTime.getTime()+i*(24*60*60*1000)))));
            this.save(sch);
        }
    }

    @Override
    public List<Schedule> getMessage(int doctorId) {
        return lambdaQuery().eq(Schedule::getDoctorId,doctorId).list();
    }

    @Override
    public void subSchedule(int id) {
        Schedule schedule=lambdaQuery().eq(Schedule::getId,id).one();
        schedule.setRemaining(schedule.getRemaining()-1);
        this.updateById(schedule);
    }
}
